import asyncio
import locale
from tokenize import String
from aiocoap import *
import netifaces

async def main():
    # # 创建CoAP客户端上下文
    # protocol = await Context.create_client_context()

    # # 构建请求消息
    # request = Message(code=GET, uri='coap://localhost/temperature')

    # try:
    #     # 发送请求并等待响应
    #     response = await protocol.request(request).response
    #     print('Result: %s\n%r' % (response.code, response.payload))
    # except Exception as e:
    #     print('Failed to fetch resource:')
    #     print(e)

    await broadcast(5683, "/qlink/success", "startCoapClientBroadcast111111")



async def broadcast(port, path, content) :
    broadcast_addresses = get_broadcast_addresses()
    for  interface, broadcast in broadcast_addresses:
        print(f"broadcast: interface = {interface}, broadcast = {broadcast}")

    for interface, broadcast in broadcast_addresses:
        url = f"coap://{broadcast}:{port}{path}"
        url1 = "coap://{0}:{1}{2}".format(broadcast, port, path)
        print(f"{url1 = }")

        
        # String.format(locale.LC_ALL, "coap://%s:%d%s", broadcast, port, path)
        print(f"broadcast: url = {url}")
        request = Message(code=POST, uri=url, payload=content)
      

        request.payload = content.encode("utf-8")
    
        print(f"broadcast: request = {request}")

        # 创建CoAP客户端上下文
        try:
            protocol = await Context.create_client_context()
            response = await protocol.request(request).response
            print(f"broadcast: response = {response.payload}")
        except Exception as e:
            print(f"broadcast: Failed to fetch resource: {e}")





#  private fun broadcast(
#         port: Int,
#         path: String,
#         content: String,
#         observerAdapter: MessageObserverAdapter
#     ) {
#         val broadcastAddress = NetworkInterfacesUtil.getBroadcastIpv4()
#         Log.d(TAG, "broadcastAddress:${broadcastAddress.hostAddress}}")
#         val url = String.format(Locale.CHINA, "coap://%s:%d%s", broadcastAddress.hostAddress, port, path)
#         Log.d(TAG, "broadcast: url=$url}")
#         val request = Request(CoAP.Code.POST, CoAP.Type.NON)
#         request.setURI(url)
#         request.setPayload(content)
#         request.addMessageObserver(observerAdapter)

#         request.send()
#     }




def get_broadcast_addresses():
    broadcast_addresses = []
    for interface in netifaces.interfaces():
        # 获取接口的地址信息
        addresses = netifaces.ifaddresses(interface)
        # 检查是否有IPv4地址
        if netifaces.AF_INET in addresses:
            for link in addresses[netifaces.AF_INET]:
                # 获取广播地址
                broadcast = link.get('broadcast')
                if broadcast:
                    broadcast_addresses.append((interface, broadcast))
    return broadcast_addresses

if __name__ == "__main__":
    # broadcasts = get_broadcast_addresses()
    # for interface, broadcast in broadcasts:
    #     print(f"Interface: {interface}, Broadcast Address: {broadcast}")

    asyncio.run(main())

